package com.lzh.main.controller;

import com.lzh.main.mapper.ChatMessageMapper;
import com.lzh.main.pojo.dto.Result;
import com.lzh.main.pojo.entity.ChatMessage;
import com.lzh.main.service.ChatService;
import com.lzh.main.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/friend-chat/")
public class ChatController {
    @Autowired
    private ChatService chatService;

    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) principal).getUser().getId();
        }
        throw new RuntimeException("无法获取用户ID");
    }

    @PostMapping("send/")
    public Result sendMessage(@RequestBody Map<String,String> data) {
        Integer receiverId = Integer.valueOf(data.get("receiverId"));
        String content = data.get("content");
        return chatService.sendMessage(getCurrentUserId(), receiverId, content);
    }

    @GetMapping("history/")
    public Result getChatHistory(@RequestParam Integer friendId) {
        return chatService.getChatHistory(getCurrentUserId(), friendId);
    }

    @GetMapping("getUnreadMessage/")
    public Result getUnreadMessages() {
        return chatService.getUnreadMessages(getCurrentUserId());
    }
}
